<?php

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
#	FILE:			includes/custom/admintools.php
#	FUNCTION:		A custom page containing useful tools for devs
#	AUTHOR:			Cameron Morrow
#	CREATED:		13/10/2005
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# Group names and IDs
$group_names = getAllGroupNames(false, true);
$group_ids = getAllGroupIDs(false, true);

# If POSTed
if (@$_POST["tool"]) {

	switch ($_POST["tool"]) {
		case "cup":

			# Get list of all pages and their sections
			$db_pages = getRecord("SELECT p_id, p_section FROM " . $PROJECT_DB_TABLES["pages"]);

			# Get list of 'physical' pages
			$physical_pages = array();

			foreach (getSectionNames() as $section_name) {
				foreach (getFiles("../" . $section_name) as $page) {
					$physical_pages[] = array(
						"p_id" => substr($page, 0, strrpos($page, ".")),
						"p_section" => $section_name
					);
				}
			}

			# Firstly see if there are any items in the DB that are not physical
			$in_db_not_in_physical = array();

			foreach ($db_pages as $db_page) {

				$found = false;

				foreach ($physical_pages as $physical_page) {
					if ($db_page["p_section"] == $physical_page["p_section"] && $db_page["p_id"] == $physical_page["p_id"]) {
						$found = true;
					}
				}

				if (!$found) {
					$in_db_not_in_physical[] = array(
						"p_id" => $db_page["p_id"],
						"p_section" => $db_page["p_section"]
					);
				}
			}

			# Secondly see if there are any physical pages that aren't in the DB
			$in_physical_not_in_db = array();

			foreach ($physical_pages as $physical_page) {

				$found = false;

				foreach ($db_pages as $db_page) {
					if ($db_page["p_section"] == $physical_page["p_section"] && $db_page["p_id"] == $physical_page["p_id"]) {
						$found = true;
					}
				}

				if (!$found) {
					$in_physical_not_in_db[] = array(
						"p_id" => $physical_page["p_id"],
						"p_section" => $physical_page["p_section"]
					);
				}
			}

			# For any pages that are in the DB, but not existing physically, add them now
			foreach ($in_db_not_in_physical as $page) {
				createContentFile($page["p_section"], $page["p_id"]);
			}

			# For any pages that exist physically but not in DB, remove them now
			foreach ($in_physical_not_in_db as $page) {
				deleteContentFile($page["p_section"], $page["p_id"]);
			}


			# Feedback
			if (count($in_db_not_in_physical) > 0) {
				foreach ($in_db_not_in_physical as $id => $page) {
					$in_db_not_in_physical[$id] = $page["p_section"] . "/" . $page["p_id"] . ".php";
				}
				$in_db_not_in_physical = implode(", ", $in_db_not_in_physical);
				addMessage("<p>Created new physical files for the following pages:</p><p>" . $in_db_not_in_physical . "</p>");
			} else {
				addMessage("<p>There are no missing physical files.</p>");
			}

			if (count($in_physical_not_in_db) > 0) {
				foreach ($in_physical_not_in_db as $id => $page) {
					$in_physical_not_in_db[$id] = $page["p_section"] . "/" . $page["p_id"] . ".php";
				}
				$in_physical_not_in_db = implode(", ", $in_physical_not_in_db);
				addMessage("<p>Deleted the following physical files which are not in the database:</p><p>" . $in_physical_not_in_db . "</p>");
			} else {
				addMessage("<p>There are no extraneous physical files.</p>");
			}

			break;

		case "missingcustom":

			# Get all pages
			$pages = getRecord("SELECT p_id, p_name, p_custom_content FROM " . $PROJECT_DB_TABLES["pages"] . " WHERE p_custom_content != ''");

			# Array of items
			$missing_pages = array();

			# For each, check for custom page
			foreach ($pages as $page) {

				if (!file_exists("../includes/custom/" . $page["p_custom_content"] . ".php") && !file_exists("../site_specific/" . $page["p_custom_content"] . ".php")) {
					$missing_pages[] = $page;
				}
			}

			# Message
			$message = array();

			foreach ($missing_pages as $missing_page) {
				$message[] = "<li>" . $missing_page["p_name"] . " (ID: " . $missing_page["p_id"] . "), custom page: " . $missing_page["p_custom_content"] . "</li>";
			}

			if (count($missing_pages) == 0) {
				addMessage("<p>There are no pages with missing custom pages.</p>");
			} else {
				addMessage("<p>The following pages have custom pages that do not exist:</p><ul>" . implode("", $message) . "</ul>", 2);
			}

			break;

		case "badaccess":

			# Get all pages
			$pages = getRecord("SELECT p_id, p_name, p_access, p_parent FROM " . $PROJECT_DB_TABLES["pages"] . " WHERE p_accesstype = 0");

			# Array of items
			$bad_pages = array();

			# For each
			foreach ($pages as $page) {

				if ($page["p_parent"] == "") {
					$bad_pages[] = $page;
				}
			}

			# Message
			$message = array();

			foreach ($bad_pages as $bad_page) {
				$message[] = "<li>" . $bad_page["p_name"] . " (ID: " . $bad_page["p_id"] . ")</li>";
			}

			if (count($bad_pages) == 0) {

				addMessage("<p>There are no pages with invalid access levels.</p>");

			} else {

				addMessage("<p>The following pages are set to inherit access levels from their parents, but do not have parents set:</p><ul>" . implode("", $message) . "</ul>", 2);
			}

			break;

		case "badparents":

			# Get all pages
			$pages = getRecord("SELECT p_id, p_name, p_parent FROM " . $PROJECT_DB_TABLES["pages"]);

			# Array of items
			$bad_pages = array();

			# For each
			foreach ($pages as $page) {

				if ($page["p_parent"] != "") {

					$found_parent = false;

					foreach ($pages as $parent_page) {
						if ($parent_page["p_id"] == $page["p_parent"]) {
							$found_parent = true;
							break;
						}
					}

					if (!$found_parent) {
						$bad_pages[] = $page;
					}
				}
			}

			# Message
			$message = array();

			foreach ($bad_pages as $bad_page) {
				$message[] = "<li>" . $bad_page["p_name"] . " (ID: " . $bad_page["p_id"] . "), parent: " . $bad_page["p_parent"] . "</li>";
			}

			if (count($bad_pages) == 0) {

				addMessage("<p>There are no pages with invalid/non-existant parents.</p>");

			} else {

				addMessage("<p>The following pages are have invalid/non-existant parents set:</p><ul>" . implode("", $message) . "</ul>", 2);
			}

			break;

		case "nogroup":

			# Get passed group
			if (@$_POST["newgroup"]) {

				# Get list of every possible group ID
				$all_group_ids = getRecord("SELECT g_id FROM " . $PROJECT_DB_TABLES["groups"]);
				$all_group_ids = extractColumnFromArray($all_group_ids, "g_id");

				# Passed
				$new_group = $_POST["newgroup"];

				# Get all users
				$users = getRecord("SELECT u_id, u_login_name, u_group FROM " . $PROJECT_DB_TABLES["users"] . " ORDER BY u_login_name ASC");

				# Bad users
				$bad_users = array();

				# For each
				foreach ($users as $user) {

					# Does this user's group exist?
					$found_group = false;

					foreach ($all_group_ids as $all_group_id) {
						if ($user["u_group"] == $all_group_id) {
							$found_group = true;
							break;
						}
					}

					# If not found
					if (!$found_group) {
						$bad_users[] = $user;
					}
				}

				# Create SQL
				$sql = array();
				foreach ($bad_users as $bad_user) {
					$sql[] = "UPDATE " . $PROJECT_DB_TABLES["users"] . " SET u_group = " . $new_group . " WHERE u_id = '" . $bad_user["u_id"] . "' LIMIT 1";
				}

				# Attempt to execute
				$sql_success = true;
				foreach ($sql as $sql_command) {
					if (!executeSQLQuery($sql_command)) {
						$sql_success = false;
					}
				}

				# Output
				if (count($sql) == 0) {
					addMessage("<p>There were no users found with non-existant groups.</p>");
				} else {

					if ($sql_success) {
						addMessage("<p>The following users had their groups reset:</p><p>" . implode(", ", extractColumnFromArray($bad_users, "u_login_name")) . "</p>");
					} else {
						addMessage("<p>An error occured and the users could not be modified. Please check the errors for more details.</p>", 1);
					}
				}

			} else {

				addMessage("<p>Sorry, an error occured and no group was passed.</p>", 2);
			}

			break;

		case "grantpermissions":

			$sql = array();

			# For each table
			foreach ($PROJECT_DB_TABLES as $table) {
				$sql[] = "GRANT ALTER, DELETE, SELECT, INSERT, UPDATE ON " . $table. " TO vs20043_1";
			}

			# Execute
			$sql_success = true;
			foreach ($sql as $sql_command) {
				if (!executeSQLQuery($sql_command)) {
					$sql_success = false;
				}
			}

			# Feedback
			if ($sql_success) {

				addMessage("<p>Permissions were granted successfully.</p>");

			} else {

				addMessage("<p>An error occured and the permissions could not be granted. Please check the errors for more details.</p>", 1);
			}

			break;
	}
}

# Tools
$tools_array = array(
	array(
		"id" => "cup",
		"name" => "Clean Up Pages",
		"desc" => "<p>Check page database and ensure there are no extraneous page files or missing page files.</p>"
	),
	array(
		"id" => "missingcustom",
		"name" => "Missing Custom Pages",
		"desc" => "<p>Check for any missing custom page handlers.</p>"
	),
	array(
		"id" => "badaccess",
		"name" => "Find Invalid Access Permissions",
		"desc" => "<p>Check for pages that are set to inherit permissions from their parents, but which don't have parents.</p>"
	),
	array(
		"id" => "badparents",
		"name" => "Find Invalid Parents",
		"desc" => "<p>Check for pages that have invalid/non-existant parents.</p>"
	),
	array(
		"id" => "nogroup",
		"name" => "Reassign Users with no group",
		"desc" => "<p>Assign any users whose group no longer exists to:</p><p>" . createSelector("newgroup", $group_names, $group_ids) . "</p>"
	)/*,
	array(
		"id" => "grantpermissions",
		"name" => "Re-grant database permissions",
		"desc" => "<p>Sometimes write permissions for the database can be lost. Use this to attempt to re-enable them.</p>"
	)*/
);

# Header
addContent("<h2>Tools</h2>");

# Intro
addContent("<p>This page contains some useful tools for maintaining the site.</p>");

# Form
addContent("<form id=\"toolform\" name=\"toolform\" action=\"" . $PAGE_ID . ".php\" method=\"post\">" .
	"<input type=\"hidden\" id=\"tool\" name=\"tool\" value=\"\" />");

# Content
addContent("<ul>");
foreach ($tools_array as $tool) {
	addContent("<li><h3>" . $tool["name"] . "</h3>" . $tool["desc"] . "<p><input type=\"button\" id=\"button" . $tool["id"] . "\" value=\"" . $tool["name"] . "\" onclick=\"callTool('" . $tool["id"] . "');\" /></p></li>");
}
addContent("</ul>");

addContent("</form>");

?>